package br.com.lh.urabuilder.command
{
	import br.com.lh.urabuilder.command.base.UraBaseCommand;
	import br.com.lh.urabuilder.domain.xml.DigitPromptAction;
	import br.com.lh.urabuilder.domain.xml.UraActionWithNext;
	import br.com.lh.urabuilder.event.LinkActionEvent;
	import br.com.lh.urabuilder.util.pointchooser.TwoComponentPointChooser;
	import br.com.lh.urabuilder.view.ActionComponent;
	import br.com.lh.urabuilder.view.arrow.ArrowContainer;
	
	import com.adobe.cairngorm.control.CairngormEvent;
	
	public class LinkActionCommand extends UraBaseCommand
	{
		private var currentArrow:ArrowContainer;	
		private var startElement:ActionComponent;
		private var endElement:ActionComponent;
		
		public function LinkActionCommand()	{
			text="linkAction"
		}
		
		public override function redo( event : CairngormEvent = null): void{
			var linkActionEvent : LinkActionEvent =	LinkActionEvent( event );
			if (linkActionEvent != null){
				startElement = linkActionEvent.startComponent;
				endElement = linkActionEvent.endComponent;
			}
			var startComponent:UraActionWithNext =startElement.uraAction as UraActionWithNext;
			if (startComponent != null){
				startComponent.setNextId(endElement.uraAction.getId());
				var arrowText:String = getVariableName(startElement);
				var bestPointChooser:TwoComponentPointChooser = new TwoComponentPointChooser(startElement,endElement);
				var pointArray:Array = bestPointChooser.pointArray;
				var arrowContainer:ArrowContainer = uraModelLocator.arrowManager.insertArrow(pointArray[0],pointArray[1]);
				uraModelLocator.arrowManager.bindStartComponent(arrowContainer,startElement);				
				uraModelLocator.arrowManager.bindEndComponent(arrowContainer,endElement);
				uraModelLocator.xmlManager.linkElements(startComponent,endElement.uraAction);
			}
		}
		
		private function getVariableName(startElement:ActionComponent):String{
			if (startElement.uraAction is DigitPromptAction){
				return DigitPromptAction(startElement.uraAction).variable.value as String;
			}
			return "";
		}
		
		
		
		
		
		public override function undo():void{
			uraModelLocator.viewManager.removeComponent(currentArrow);
		}
		
		
		

	}
}